<script lang="ts" setup>
import {useInfoStore} from "@/store/user/user.ts";
import type {UnwrapRef} from 'vue';
import {onMounted, reactive, ref, toRaw} from "vue";
//上传头像
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons-vue';
import type {UploadChangeParam, UploadProps} from 'ant-design-vue';
import {message} from 'ant-design-vue';
//基本信息
import type {Rule} from 'ant-design-vue/es/form';
import {deleteAvatarAPI, resetPasswordAPI} from "@/apis/user.ts";
import {useRouter} from "vue-router";
import {queryAdminPersonalAPI, updateAdminPersonalAPI} from "@/apis/admin.ts";

//生命周期
onMounted(() => {
  queryAdminPersonal();
})

//用户信息
const userStore = useInfoStore().userInfo;
const userInfo = reactive({
  userId: userStore.userId,
  userName: userStore.userName === null ? '未设置' : userStore.userName,
  userAvatarUrl: userStore.userAvatarUrl === null ? 'https://tse4-mm.cn.bing.net/th/id/OIP-C.cTPVthB0oT1RXrEcSHaaTwHaHa?w=202&h=201&c=7&r=0&o=5&dpr=2.5&pid=1.7' : 'http://localhost:8080/image/download?name=' + userStore.userAvatarUrl,
  account: userStore.account,
  userRole: userStore.userRole,
  userStatus: userStore.userStatus,
  userIsVerified: userStore.userIsVerified, //是否认证
});
//查询求职者个人信息
// 是否修改了头像
const isUpdateAvatar = (userAvatarUrl: string) => {
  if (userAvatarUrl !== userStore.userAvatarUrl) {
    //修改了头像
    //删除原来的头像
    if (userStore.userAvatarUrl !== null) {
      deleteAvatarAPI(userStore.userAvatarUrl);
    }
    useInfoStore().setUserAvatarUrl(userAvatarUrl);
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);

  }
};
//是否修改了昵称
const isUpdateUsername = (userName: string) => {
  if (userName !== userInfo.userName) {
    //修改了昵称
    useInfoStore().setUserName(userName);
    userInfo.userName = userName;
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);
  }
}
const queryAdminPersonal = async () => {
  const res = await queryAdminPersonalAPI(userInfo.userId);
  if (res.data.flag) {
    console.log(res.data.data);
    formState.adminId = userInfo.userId;
    formState.adminStatus = res.data.data.adminStatus;
    formState.adminUsername = res.data.data.adminUsername;
    formState.userAvatarUrl = res.data.data.userAvatarUrl;
    formState.adminAccount = res.data.data.adminAccount;
    formState.adminRole = res.data.data.adminRole;
    formState.adminPhone = res.data.data.adminPhone;

    //获取头像
    if (formState.userAvatarUrl !== null) {
      imageUrl.value = "http://localhost:8080/image/download?name=" + formState.userAvatarUrl;
    }
  }
}


function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref<boolean>(false);
const imageUrl = ref<string>('');

const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = base64Url;
      loading.value = false;

    });
    console.log("url:" + fileList.value[0].response.data);
    formState.userAvatarUrl = fileList.value[0].response.data;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};

const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

interface FormState {
  adminId: string;
  adminStatus: string;
  adminUsername: string;
  adminAccount: string;
  userAvatarUrl: string;
  adminPhone: string;
  adminRole: string;
}

const formRef = ref();
const labelCol = {span: 5};
const wrapperCol = {span: 13};
const formState: UnwrapRef<FormState> = reactive({
  adminId: '',
  adminStatus: '',
  adminUsername: '',
  adminAccount: '',
  userAvatarUrl: '',
  adminPhone: '',
  adminRole: '',
});
const rules: Record<string, Rule[]> = {
  adminUsername: [
    {required: true, message: '请输入你的用户昵称', trigger: 'change'},
    {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change'},
  ],
};
//修改雇主个人信息
const onSubmit = () => {
  formRef.value
      .validate()
      .then(async () => {
        console.log('values', formState, toRaw(formState));
        const res = await updateAdminPersonalAPI(formState);
        if (res.data.flag) {
          isUpdateAvatar(formState.userAvatarUrl);
          isUpdateUsername(formState.adminUsername);
          message.success('修改成功');
        }
      })
      .catch((error: string) => {
        console.log('error', error);
      });
};
const resetForm = () => {
  formRef.value.resetFields();
};

//重置密码
interface FormStatePassword {
  password1: string;
  password2: string;
}

const formRefPassword = ref();
const FormStatePassword = reactive<FormStatePassword>({
  password1: '',
  password2: '',
});
const open = ref<boolean>(false);
const router = useRouter();
const resetPassword = () => {
  open.value = true;
  formRefPassword.value.resetFields();
}
const handleOk = async (e: MouseEvent) => {
  console.log(e);
  //判断两个密码是否一致
  if (FormStatePassword.password1 !== FormStatePassword.password2) {
    message.error('两次输入的密码不一致');
  } else {
    const res = await resetPasswordAPI(userInfo.account, FormStatePassword.password1, userInfo.userRole);
    if (res.data.flag) {
      message.success('密码修改成功');
      // 设置一个定时器，1秒（1000毫秒）后执行页面跳转
      setTimeout(async function () {
        await router.replace('/login');
      }, 1000);
    } else {
      message.error('密码修改失败');
    }
  }
  open.value = false;
};

</script>

<template>
  <div class="jobseeker_personal">
    <div class="content">
      <div class="top">
        <a-page-header
            :avatar="{ src:userInfo.userAvatarUrl , size:54} "
            :title="userInfo.userName"
            style="padding: 0"
            sub-title="个人中心"
            @back="() => $router.go(-1)"
        />
        <div style="display: flex;justify-content: space-around;width: 100%;padding-right: 20%">
          <div>账号: {{ userInfo.account }}</div>
        </div>

      </div>
      <div class="main">
        <div class="left">
          <a-divider orientation="left" style="color:#4D7181; font-size: 20px">基本信息</a-divider>
          <a-form
              ref="formRef"
              :label-col="labelCol"
              :model="formState"
              :rules="rules"
              :wrapper-col="wrapperCol"
          >
            <a-form-item ref="adminUsername" label="用户昵称" name="adminUsername">
              <a-input v-model:value="formState.adminUsername"/>
            </a-form-item>
            <a-form-item ref="adminPhone" label="手机号码" name="adminPhone">
              <a-input v-model:value="formState.adminPhone"/>
            </a-form-item>
            <div class="form-button">
              <a-button type="primary" @click="onSubmit">保存修改</a-button>
              <a-button @click="resetForm">重置表单</a-button>
              <a-button danger type="primary" @click="resetPassword">重置密码</a-button>
            </div>
          </a-form>

          <!--          重置密码弹窗-->
          <div>
            <a-modal v-model:open="open"
                     cancelText="取消"
                     okText="确认重置"
                     title="重置密码"
                     @ok="handleOk">
              <div style="padding: 20px">
                <a-form
                    ref="formRefPassword"
                    :model="FormStatePassword"
                >
                  <a-form-item
                      :rules="[
                    { required: true, message: '请输入你的新密码!' },
                { min: 6, message: '密码长度不能小于6位' },
                { max: 10, message: '密码长度不能大于10位'},
                { pattern: /^\S+$/, message: '密码不能包含空格' }
                    ]"
                      label="输入新密码"
                      name="password1"
                  >
                    <a-input-password v-model:value="FormStatePassword.password1" :visibilityToggle="false"/>
                  </a-form-item>

                  <a-form-item
                      :rules="[
                    { required: true, message: '请确认你的新密码!' },
                { min: 6, message: '密码长度不能小于6位' },
                { max: 10, message: '密码长度不能大于10位'},
                { pattern: /^\S+$/, message: '密码不能包含空格' }
                    ]"
                      label="确认新密码"
                      name="password2"
                  >
                    <a-input-password v-model:value="FormStatePassword.password2" :visibilityToggle="false"/>
                  </a-form-item>

                </a-form>
              </div>
            </a-modal>
          </div>


        </div>
        <div class="right">
          <div class="update-avatar">
            <a-upload
                v-model:file-list="fileList"
                :before-upload="beforeUpload"
                :show-upload-list="false"
                action="http://localhost:8080/image/upload"
                class="avatar-uploader"
                list-type="picture-card"
                name="file"
                @change="handleChange"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="width: 150px; height: 150px;border-radius: 50%"/>
              <div v-else>
                <loading-outlined v-if="loading"></loading-outlined>
                <plus-outlined v-else></plus-outlined>
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </div>

        </div>

      </div>
    </div>
  </div>

</template>

<style scoped>
.jobseeker_personal {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f0f2f5;

  .content {
    display: flex;
    flex-direction: column;
    width: 60%;
    height: 800px;
    background-color: #ffffff;
    box-sizing: border-box; /* 确保边框不会增加额外宽度 */


    .top {
      display: flex;
      align-items: center;
      height: auto;
      padding-left: 20px;
      margin-bottom: 50px;
    }

    .main {
      display: flex;
      height: 80%;

      .left {
        width: 70%;
        height: 100%;
        padding: 0 10px;

        .form-button {
          margin-left: 35px;
          width: 70%;
          display: flex;
          justify-content: right;
          gap: 10px; /* 设置子元素之间的间距为 10px */
        }
      }

      .right {
        width: 30%;
        height: 100%;

        .update-avatar {
          width: auto;
          height: auto;

          .avatar-uploader {
            width: 170px;
            height: 170px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }

}

</style>
